package com.csii.modules.system.controller;

import javax.servlet.http.HttpServletRequest;

import com.csii.core.api.Result;
import com.csii.core.util.TenantContext;
import com.csii.modules.system.mapper.SysDictMapper;
import com.csii.modules.system.model.DuplicateCheckVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Title: DuplicateCheckAction
 * @Description: 重复校验工具
 * @Author 张代浩
 * @Date 2019-03-25
 * @Version V1.0
 */
@Slf4j
@RestController
@RequestMapping("/sys/duplicate")
@Api(tags="重复校验")
public class DuplicateCheckController {

	@Autowired
	SysDictMapper sysDictMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 校验数据是否在系统中是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.GET)
	@ApiOperation("重复校验接口")
	public Result<Object> doDuplicateCheck(DuplicateCheckVo duplicateCheckVo, HttpServletRequest request) {
		Long num = null;

		log.info("----duplicate check------："+ duplicateCheckVo.toString());
		//如果是校验username 就让他查询全部的数据
		if (isUserName(duplicateCheckVo)) {
			TenantContext.setTenant(null);
		}
		if (StringUtils.isNotBlank(duplicateCheckVo.getDataId())) {
			// [2].编辑页面校验
			//SQL注入 num = sysDictMapper.duplicateCheckCountSql(duplicateCheckVo);
			String sql = "SELECT COUNT(*) FROM "+ duplicateCheckVo.getTableName() +" WHERE "+ duplicateCheckVo.getFieldName() + " = " + duplicateCheckVo.getFieldVal() +" and id <> "+ duplicateCheckVo.getDataId();
			num = jdbcTemplate.queryForObject(sql, Long.class);
		} else {
			// [1].添加页面校验
			//SQL注入 num = sysDictMapper.duplicateCheckCountSqlNoDataId(duplicateCheckVo);
			String sql = "SELECT COUNT(*) FROM "+ duplicateCheckVo.getTableName() +" WHERE "+ duplicateCheckVo.getFieldName() +" = "+ duplicateCheckVo.getFieldVal();
			num = jdbcTemplate.queryForObject(sql, Long.class);
		}

		if (num == null || num == 0) {
			// 该值可用
			return Result.ok("该值可用！");
		} else {
			// 该值不可用
			log.info("该值不可用，系统中已存在！");
			return Result.error("该值不可用，系统中已存在！");
		}
	}
	private boolean isUserName(DuplicateCheckVo duplicateCheckVo){
		if (duplicateCheckVo.getTableName().equals("sys_user") && duplicateCheckVo.getFieldName().equals("username")){
			return true;
		}
		return false;
	}

}
